import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/components/passagemodule.dart';
import 'package:wayofdressing/components/choosebutton.dart';
import 'package:wayofdressing/components/inmenubutton.dart';
import 'package:wayofdressing/dio/PostDio.dart';
import 'package:wayofdressing/dio/UserDetailDio.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:wayofdressing/good_method/decode_base64_to_bytes.dart';
import 'package:wayofdressing/screens/publish_screen.dart';

class CommunityScreen extends StatefulWidget {
  static final String id = 'community';

  @override
  State<CommunityScreen> createState() => _CommunityScreenState();
}

class _CommunityScreenState extends State<CommunityScreen> {
  MenuController menuController = MenuController();
  int whoisactive = 1;
  List<Widget> posts = [];
  List<Widget> widgetList = [];
  List<String> circleCategories = [];
  bool isLoad=false;
  Map<String, List<Widget>> circles = {
    '二次元': [],
    '古装': [],
    '户外': [],
    '潮牌': [],
    '古着': [],
    '朋克': [],
    '时装': [],
  };
  bool isCommunity = true;
  ImageProvider postImage = AssetImage('images/peanut.jpg');
  ImageProvider authorHeadImage = AssetImage('images/peanut.jpg');
  TextEditingController textController = TextEditingController();

  Future _loadAllPosts() async {
    try {
      Response response = await getAllPosts(dio: dio);
      dynamic data = response.data['data'];
      List<Widget> loadingPosts=[];
      for (dynamic item in data) {
        String title = item['title'];
        String content = item['content'];
        int sharesCount = item['sharesCount'];
        int likesCount = item['likesCount'];
        int commentsCount = item['commentsCount'];
        int favoritesCount = item['favoritesCount'];
        int authorId = item['userDTO']['id'];
        String authorName = item['userDTO']['name'];
        Map<String, dynamic> postInfo = {
          'title': title,
          'content': content,
          'likesCount': likesCount,
          'sharesCount': sharesCount,
          'commentsCount': commentsCount,
          'favoritesCount': favoritesCount,
          'authorId': authorId,
          'authorName': authorName,
        };
        Response responseUserDetail =
            await getUserDetailByUserId(userId: authorId, dio: dio);
        dynamic authorDetail = responseUserDetail.data['data'];
        String? base64Image = item['imageBytes'];
        String? base64AuthorHeadImage = authorDetail['imageBytes'];
        if (base64AuthorHeadImage != null && base64AuthorHeadImage.isNotEmpty) {
          Uint8List imageBytes = decodeBase64ToBytes(base64AuthorHeadImage);
          authorHeadImage = MemoryImage(imageBytes);
        }
        if (base64Image != null && base64Image.isNotEmpty) {
          Uint8List imageBytes = decodeBase64ToBytes(base64Image);
          postImage = MemoryImage(imageBytes);
        }
        loadingPosts.add(CreatePostWidget(postInfo));
      }
      setState(() {
        posts=loadingPosts;
        isLoad=true;
      });
    } on Exception catch (e) {
      print(e);
    }
  }

  Widget CreatePostWidget(Map<String, dynamic> postInfo) {
    return PassageModule(
      image: postImage,
      headImage: authorHeadImage,
      postInfo: postInfo,
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // posts = [
    //   PassageModule(
    //       text: '',
    //       like: 123,
    //       authorName: '程天然',
    //       headImage: AssetImage('images/ctr.jpg'),
    //       title: 'NIKE标准色卡，SP/SU 2012 GYM',
    //       image: AssetImage('images/dc.png'),
    //       postInfo: {}),
    //   PassageModule(
    //       text: '',
    //       like: 1000,
    //       authorName: '舒程锦',
    //       headImage: AssetImage('images/scj.jpg'),
    //       title: '家人们，这个卫生巾我亲测超好用！',
    //       image: AssetImage('images/naying.png'),
    //       postInfo: {}),
    //   PassageModule(
    //       text: '',
    //       like: 678,
    //       authorName: '胡月冰',
    //       headImage: AssetImage('images/hyb.jpg'),
    //       title: '兄弟们，工作的时候穿这套衣服，加班都变有趣了！',
    //       image: AssetImage('images/wojiu.png'),
    //       postInfo: {}),
    //   PassageModule(
    //       text: '',
    //       like: 10,
    //       authorName: '刘子璇',
    //       headImage: AssetImage('images/lzx.jpg'),
    //       title: '有没有一起学习穿搭技巧的朋友？',
    //       image: AssetImage('images/laoshi.png'),
    //       postInfo: {}),
    //   PassageModule(
    //       text: '',
    //       like: 123,
    //       authorName: '梁嘉伦',
    //       headImage: AssetImage('images/ljl.jpg'),
    //       title: '有会首页Ai的隐藏用法的吗？求教学！',
    //       image: AssetImage('images/tuiqian.png'),
    //       postInfo: {}),
    //   PassageModule(
    //       text: '',
    //       like: 1000,
    //       authorName: '邓超',
    //       headImage: AssetImage('images/dc.png'),
    //       title: '是谁到处发我的表情包？小心我告你侵权',
    //       image: AssetImage('images/dc.png'),
    //       postInfo: {}),
    // ];
    circleCategories = circles.keys.toList();
    _loadAllPosts();
  }

  @override
  void dispose() {
    textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 60,
        centerTitle: true,
        title: Container(
          height: 36,
          margin: EdgeInsets.symmetric(horizontal: 20.0),
          decoration: BoxDecoration(
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.2),
                // 阴影颜色和透明度
                spreadRadius: 2,
                // 阴影扩展半径
                blurRadius: 5,
                // 阴影模糊半径
                offset: Offset(0, 2), // 阴影偏移量
              ),
            ],
            color: Colors.white,
            borderRadius: BorderRadius.circular(25.0),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextButton(
                  style: ButtonStyle(
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25),
                        ),
                      ),
                      backgroundColor: isCommunity
                          ? MaterialStateProperty.all(Colors.orange)
                          : MaterialStateProperty.all(Colors.transparent)),
                  onPressed: () {
                    setState(() {
                      isCommunity = true;
                    });
                  },
                  child: Text(
                    '社区',
                    style: TextStyle(
                      color: isCommunity ? Colors.white : Colors.black,
                      fontSize: 17,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: TextButton(
                  style: ButtonStyle(
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25),
                        ),
                      ),
                      backgroundColor: !isCommunity
                          ? MaterialStateProperty.all(Colors.orange)
                          : MaterialStateProperty.all(Colors.transparent)),
                  onPressed: () {
                    setState(() {
                      isCommunity = false;
                    });
                  },
                  child: Text(
                    '圈子',
                    style: TextStyle(
                      color: !isCommunity ? Colors.white : Colors.black,
                      fontSize: 17,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        leading: Row(
          children: [
            SizedBox(
              width: 10,
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Transform.scale(
                scaleX: -1,
                child: Icon(
                  Icons.play_arrow_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black.withOpacity(0.5),
                ),
              ),
            ),
          ],
        ),
        actions: [
          MenuAnchor(
            controller: menuController,
            menuChildren: [
              InMenuButton(
                onPressed: () {
                  showModalBottomSheet(
                      isScrollControlled: true,
                      context: context,
                      builder: (context) => PublishScreen()).then((_) {
                    if (isPost) {
                      isPost=false;
                      _loadAllPosts();
                    }
                  });
                  menuController.close();
                },
                text: '发布帖子',
                alignment: Alignment.centerRight,
              ),
            ],
            style: MenuStyle(
              shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
              alignment: Alignment(-3, 0.5),
              padding: MaterialStateProperty.all(EdgeInsets.all(15.0)),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
              backgroundColor: MaterialStateProperty.all(
                Colors.black.withOpacity(0.4),
              ),
            ),
            builder: (BuildContext context, MenuController controller,
                Widget? child) {
              return GestureDetector(
                onTap: () {
                  if (controller.isOpen) {
                    controller.close();
                  } else {
                    controller.open();
                  }
                },
                child: Icon(
                  Icons.keyboard_control_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black,
                ),
              );
            },
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Stack(
        alignment: Alignment(0, 0),
        children: [
          Column(
            children: [
              !isCommunity
                  ? Container(
                      height: 36,
                      margin: EdgeInsets.symmetric(horizontal: 30),
                      decoration: BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.2),
                            // 阴影颜色和透明度
                            spreadRadius: 2,
                            // 阴影扩展半径
                            blurRadius: 5,
                            // 阴影模糊半径
                            offset: Offset(0, 2), // 阴影偏移量
                          ),
                        ],
                        borderRadius: BorderRadius.circular(25),
                        color: Colors.white,
                      ),
                      child: ListView.builder(
                          itemCount: circleCategories.length,
                          scrollDirection: Axis.horizontal,
                          itemBuilder: (context, index) {
                            return chooseButton(
                              isActive: whoisactive,
                              text: circleCategories[index],
                              listNumber: index,
                              onPressed: () {
                                setState(() {
                                  whoisactive = index;
                                  widgetList =
                                      circles[circleCategories[index]]!;
                                });
                              },
                            );
                          }),
                    )
                  : SizedBox(),
              Expanded(
                  child: isCommunity
                      ? isLoad?GridView.builder(
                        itemCount: posts.length,
                        gridDelegate:
                            SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2,
                          mainAxisSpacing: 8,
                          childAspectRatio: 1 / 1.5,
                        ),
                        itemBuilder: (BuildContext context, index) =>
                            posts[index],
                      ):Center(child: CircularProgressIndicator())
                      : SizedBox())
            ],
          ),
          Positioned(
            bottom: -10,
            child: Container(
              height: 50,
              width: 240,
              margin: EdgeInsets.symmetric(horizontal: 50, vertical: 30),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.3),
                borderRadius: BorderRadius.circular(40.0),
              ),
              child: TextField(
                controller: textController,
                showCursor: false,
                textAlign: TextAlign.center,
                cursorColor: Colors.black,
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 22,
                ),
                decoration: InputDecoration(
                  suffixIcon: GestureDetector(
                    onTap: () {
                      setState(() {
                        textController.clear();
                      });
                    },
                    child: Icon(
                      Icons.search_rounded,
                      size: 50,
                      color: Colors.white,
                    ),
                  ),
                  border: InputBorder.none,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
